package com.keiou.drink.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.keiou.drink.R;
import com.keiou.drink.api.AbsSubscriber;
import com.keiou.drink.api.exception.ApiException;
import com.keiou.drink.api.remote.Api;
import com.keiou.drink.api.rx.RxHelper;
import com.keiou.drink.glide.GlideUtil;
import com.keiou.drink.response.ProductListRes;
import com.keiou.drink.response.base.HttpResult;
import com.keiou.drink.ui.activity.base.RxActivity;
import com.keiou.drink.util.CToast;
import com.keiou.drink.util.PrefsHelper;
import com.keiou.drink.util.TDevice;
import com.keiou.drink.util.TLog;
import com.keiou.drink.util.UIUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import rx.Subscription;

public class MainActivity extends RxActivity implements EasyPermissions.PermissionCallbacks {

    private static final int RC_REQUEST_READ_PHONE_STATE = 1001;
    @BindView(R.id.iv_manager)
    ImageView ivManager;
    @BindView(R.id.iv_place_1)
    ImageView ivPlace1;
    @BindView(R.id.iv_place_2)
    ImageView ivPlace2;
    @BindView(R.id.iv_place_3)
    ImageView ivPlace3;
    @BindView(R.id.iv_place_4)
    ImageView ivPlace4;
    @BindView(R.id.iv_place_5)
    ImageView ivPlace5;
    @BindView(R.id.iv_place_6)
    ImageView ivPlace6;
    @BindView(R.id.iv_place_7)
    ImageView ivPlace7;
    @BindView(R.id.iv_place_8)
    ImageView ivPlace8;
    @BindView(R.id.iv_place_9)
    ImageView ivPlace9;
    @BindView(R.id.iv_place_10)
    ImageView ivPlace10;

    private ImageView[] ivPlaces;

    private List<ProductListRes.ProductsBean> data = new ArrayList<>();

    private boolean isLoading = false;

    Subscription subscription;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        initPlaceItem();
        isLoading = false;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    private void initPlaceItem() {
        ivPlaces = new ImageView[]{ivPlace1, ivPlace2, ivPlace3, ivPlace4, ivPlace5, ivPlace6, ivPlace7, ivPlace8, ivPlace9, ivPlace10};

        int position = 0;
        for (ImageView iv : ivPlaces) {
            int finalPosition = position;
            iv.setOnClickListener(v -> {
                onItemClick(finalPosition);
            });
            position++;
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void loadData() {

    }

    @Override
    protected void onResume() {
        super.onResume();

//        if (null != subscription && !subscription.isUnsubscribed()) {
//            subscription.unsubscribe();
//        }
        if (!isLoading) {
            loadContactsSelf();
        }

        //防止意外导致isLoading一直为true。
        isLoading = false;
    }

    /**
     * 加载商品
     */
    private void loadShop() {
        String deviceId = PrefsHelper.getDeviceId(this);
        isLoading = true;

        if (data.isEmpty()) {
            showLoadingDialog();
        }
        subscription = Api.getInstance().getProductList(deviceId)
                .compose(RxHelper.applySchedulers())
                .subscribe(new AbsSubscriber<HttpResult<ProductListRes>>() {
                    @Override
                    public void onNext(HttpResult<ProductListRes> result) {
                        isLoading = false;
                        data.clear();

                        List<ProductListRes.ProductsBean> tempList = result.getResult().getProducts();
                        String baseUrl = result.getResult().getImgRootUrl();
                        for (int i = 0; null != tempList && i < tempList.size(); i++) {
                            ProductListRes.ProductsBean bean = tempList.get(i);
                            bean.setMainPic(baseUrl + bean.getMainPic());
                            data.add(bean);
                        }
                        notifyDatasetChanged();
                        hideWaitDialog();
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        isLoading = false;
                        if (data.isEmpty()) {
                            CToast.showShort(MainActivity.this, ex.getMsg());
                        }
                        hideWaitDialog();
                    }

                    @Override
                    protected void onIntercept(int code) {
                        isLoading = false;
                        onInterceptCode(code);
                    }
                });

        addSubscribe(subscription);
    }


    @OnClick({R.id.iv_manager})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_manager:
                UIUtil.redirectTo(MainActivity.this, LoginActivity.class);
                break;

        }
    }


    /**
     * 跳转到选择界面
     *
     * @param position
     */
    private void onItemClick(int position) {

        if (data.size() > position) {
            ProductListRes.ProductsBean productsBean = data.get(position);
            Intent intent = new Intent(this, ConfirmActivity.class);
            intent.putExtra("product", productsBean);
            startActivity(intent);
        }


    }

    /**
     * 刷新界面
     */
    private void notifyDatasetChanged() {
        int position = 0;
        for (ImageView iv : ivPlaces) {
            if (position <= data.size()) {
                if (iv.getVisibility() == View.INVISIBLE) iv.setVisibility(View.VISIBLE);
                ProductListRes.ProductsBean bean = data.get(position);
                // bean.setMainPic("http://p2.qhimgs4.com/t011281a93d81933c8a.webp");
                GlideUtil.loadImagefitCrop(this, bean.getMainPic(), iv);

            } else {
                if (iv.getVisibility() == View.VISIBLE) iv.setVisibility(View.INVISIBLE);
            }
            position++;
        }
    }


    @AfterPermissionGranted(RC_REQUEST_READ_PHONE_STATE)
    public void loadContactsSelf() {
        String perm = Manifest.permission.READ_PHONE_STATE;
        if (!EasyPermissions.hasPermissions(this, perm)) {
            EasyPermissions.requestPermissions(this, "获取手机状态的权限.",
                    RC_REQUEST_READ_PHONE_STATE, perm);
        } else {
            loadShop();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        CToast.showShort(MainActivity.this, "没有权限, 你需要去设置中开启允许读取手机状态的权限.");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }
}
